import mysql.connector
from mysql.connector import Error
import uuid
import random
from datetime import datetime
from common import snowFaker as sf
from datetime import datetime, timedelta

from python_faker.faker06 import getUserIdList
from python_faker.faker14 import get_flavor_ids_by_dish_id
from python_faker.faker15 import get_specification_ids_by_dish_id
# 在原有订单创建函数中修改金额计算部分
from decimal import Decimal, ROUND_HALF_UP

from python_faker.test import generate_order_time


def create_order(user_id):
    """为指定用户创建完整订单"""
    connection = None
    try:
        # 连接配置
        connection = mysql.connector.connect(
            host="localhost",
            user="root",
            password="123456",
            database="esl"
        )
        connection.start_transaction()  # 开启事务

        cursor = connection.cursor(dictionary=True)

        # ========== 1. 生成基础数据 ==========
        order_id = str(uuid.uuid4()).replace('-', '')  # 生成唯一订单ID
        # current_time = datetime.now()  # 订单时间
        current_time = generate_order_time()
        # 随机生成0-5小时的时间差（含小数）
        time_delta = timedelta(
            hours=random.uniform(0, 5),
            minutes=random.randint(0, 59)
        )
        finish_time = current_time + time_delta
        canteen_id = None  # 需要后续获取

        # ========== 2. 获取必要关联数据 ==========
        # 2.1 获取用户地址（随机选一个）
        cursor.execute("""
            SELECT address_id 
            FROM address 
            WHERE user_id = %s 
            ORDER BY RAND() 
            LIMIT 1
        """, (user_id,))
        address = cursor.fetchone()
        if not address:
            raise Exception("用户没有可用地址")

        # 2.2 获取同一食堂的菜品（参考之前逻辑）
        # 获取有足够菜品的食堂
        cursor.execute("""
            SELECT canteen_id 
            FROM dish 
            GROUP BY canteen_id 
            HAVING COUNT(*) >= 3 
            ORDER BY RAND() 
            LIMIT 1
        """)
        canteen = cursor.fetchone()
        if not canteen:
            raise Exception("没有符合条件的食堂")
        canteen_id = canteen['canteen_id']

        # 随机选3个菜品
        cursor.execute("""
            SELECT dish_id, price 
            FROM dish 
            WHERE canteen_id = %s 
            ORDER BY RAND() 
            LIMIT 3
        """, (canteen_id,))
        dishes = cursor.fetchall()

        # ========== 3. 计算订单金额 ==========
        # commodity_money = sum(dish['price'] for dish in dishes)  # 模拟数量为1
        # delivery_money = 5.00 if commodity_money < 30 else 0.00  # 满30免运费
        # packaging_money = 2.00
        # discounts = random.uniform(0, 5)  # 随机优惠0-5元
        # pay_money = commodity_money + delivery_money + packaging_money - discounts

        commodity_money, delivery_money, packaging_money, discounts, pay_money = calculate_order_amounts(dishes)
        # ========== 4. 插入orderdetail表 ==========
        order_detail_data = {
            'id': sf.get_id(),  # 实际应使用更健壮的ID生成方式
            'order_id': order_id,
            'user_id': user_id,
            'order_time': current_time,
            'finish_time': finish_time,  # 订单未完成
            'address_id': address['address_id'],
            'commodity_money': commodity_money,
            'delivery_money': delivery_money,
            'packaging_money': packaging_money,
            'pay_money': pay_money,  # 防止负数
            'discounts': discounts,
            'order_remark': "大吉大利，今晚吃鸡",  # 示例备注
            'canteen_id': canteen_id,
            'tag_id': random.choice(['8', '9', '10', '11', '12']),
            'pay_id': random.choice(['1', '2', '3', '4']),
            'deliveryman_id': None
        }

        cursor.execute("""
            INSERT INTO orderdetail (
                id, order_id, user_id, order_time, finish_time,
                address_id, commodity_money, delivery_money,
                packaging_money, pay_money, discounts, order_remark,
                tag_id, pay_id, deliveryman_id, canteen_id
            ) VALUES (
                %(id)s, %(order_id)s, %(user_id)s, %(order_time)s, %(finish_time)s,
                %(address_id)s, %(commodity_money)s, %(delivery_money)s,
                %(packaging_money)s, %(pay_money)s, %(discounts)s, %(order_remark)s,
                %(tag_id)s, %(pay_id)s, %(deliveryman_id)s, %(canteen_id)s
            )
        """, order_detail_data)

        # ========== 5. 插入order_dish表 ==========
        for idx, dish in enumerate(dishes):
            flavor_ids = get_flavor_ids_by_dish_id(dish['dish_id'])
            flavor_id = random.choice(flavor_ids) if flavor_ids else None
            specification_ids = get_specification_ids_by_dish_id(dish['dish_id'])
            specification_id = random.choice(specification_ids) if specification_ids else None
            order_dish_data = {
                'id': sf.get_id(),  # 子ID生成方式
                'order_id': order_id,
                'dish_id': dish['dish_id'],
                'quantity': 1,  # 默认数量
                'flavor_id': flavor_id,
                'specification_id': specification_id
            }

            cursor.execute("""
                INSERT INTO order_dish (
                    id, order_id, dish_id, quantity,
                    flavor_id, specification_id
                ) VALUES (
                    %(id)s, %(order_id)s, %(dish_id)s, %(quantity)s,
                    %(flavor_id)s, %(specification_id)s
                )
            """, order_dish_data)

        connection.commit()  # 提交事务
        print(f"订单 {order_id} 创建成功")

    except Error as e:
        if connection:
            connection.rollback()  # 回滚事务
        print("数据库操作失败:", e)
    except Exception as e:
        if connection:
            connection.rollback()
        print("业务逻辑错误:", e)
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()


# 金额计算修正逻辑
def calculate_order_amounts(dishes):
    """统一处理金额计算（返回 Decimal 类型）"""
    # 商品总金额（假设 dishes 中 price 字段可能是 float 或 Decimal）
    commodity_money = sum(
        Decimal(str(dish['price'])) for dish in dishes
    ).quantize(Decimal('0.00'))

    # 配送费逻辑
    delivery_money = Decimal('5.00') if commodity_money < Decimal('30.00') else Decimal('0.00')

    # 包装费
    packaging_money = Decimal('2.00')

    # 随机优惠（保留两位小数）
    discounts = Decimal(
        str(random.uniform(0, 5))
    ).quantize(Decimal('0.00'), rounding=ROUND_HALF_UP)

    # 应付金额
    pay_money = (
            commodity_money
            + delivery_money
            + packaging_money
            - discounts
    ).quantize(Decimal('0.00'))

    # 确保非负
    pay_money = max(pay_money, Decimal('0.00'))

    return {'commodity_money': commodity_money, 'delivery_money': delivery_money, 'packaging_money': packaging_money,
            'discounts': discounts, 'pay_money': pay_money}


# 使用示例
if __name__ == "__main__":
    # create_order("3159c45e88384c1889fe487248af0e1b")  # 替换为实际 user_id
    userIds = getUserIdList()
    for i, id in enumerate(userIds):
        create_order(id[0])
        print(f"已插入第{i + 1}条订单数据")
